<template>
  <div class="body">
    <div class="chat-box">
      <!-- 消息盒子头部 -->
      <div class="chat-box-top">
        {{ $t('chat.messageBox') }}
        <span class="user-name">{{ userName }}</span>
      </div>

      <div class="chat-box-main">
        <!-- 消息盒子左侧栏 -->
        <div class="chat-box-left">
          <!-- 左侧用户信息栏 -->
          <Conversation
            ref="conversationRef"
            :on-select-channel="onSelectChannel"
            @channel-info-update="channelInfoUpdate"
          />
        </div>

        <!-- 消息盒子右侧信息回复栏 -->
        <div class="chat-box-right">
          <div class="im-box">
            <div class="im-main">
              <div class="chat-main-form">
                <div class="display-infor">
                  <div
                    ref="chatRef"
                    class="message-list"
                    @scroll="handleScroll"
                  >
                    <template
                      v-for="(m, index) in messages"
                      :key="index"
                    >
                      <div
                        v-if="m.timeStr"
                        class="topTime"
                      >
                        {{ m.timeStr }}
                      </div>

                      <div
                        v-if="m.send||m.content.text.sender||m.content.text?.msgType===-1||m.content.text?.type===-1"
                        :id="m.clientMsgNo"
                        class="message right"
                      >
                        <div
                          v-if="m.content.text.sender===1"
                          class="divider-box"
                        >
                          <div class="divider" />
                          <div class="divider-txt">
                            {{ $t('chat.transferToCustomerService') }}{{ getChannelInfo(m,'nickName') }}
                          </div>
                          <div class="divider" />
                        </div>
                        <div class="message-content">
                          <div class="username">
                            {{ getChannelInfo(m,'nickName') }}
                          </div>
                          <div class="read-status">
                            <div
                              v-if="maxReadSeq>=m.messageSeq"
                            >
                              已读
                            </div>
                            <div
                              v-else
                            >
                              未读
                            </div>
                          </div>

                          <div class="bubble-right">
                            <div
                              v-if="(m.content.text.msgType===-1||m.content.text.msgType===1||m.content.text.type===-5)&&m.content.text.type!==-1"
                              class="bubble-content"
                            >
                              {{ m.content.text.msg }}
                            </div>
                            <div
                              v-if="m.content.text.msgType===2"
                              class="bubble-content"
                              @tap="showPic(checkFileUrl(m.content.text.msg))"
                            >
                              <el-image
                                :src="checkFileUrl(m.content.text.msg)"
                                class="longimage"
                                :preview-src-list="[checkFileUrl(m.content.text.msg)]"
                              />
                            </div>
                            <div
                              v-if="m.content.text.type===-1"
                              class="bubble-content"
                            >
                              <div
                                v-if="m.content.text.sendTextState"
                              >
                                {{ m.content.text.content }}
                              </div>
                              <div
                                v-if="m.content.text.sendIssusState"
                                style="display: flex; flex-direction: column;align-items: flex-start;"
                              >
                                <div
                                  v-for="item in m.content.text.issues"
                                  :key="item.id"
                                  class="issues-btn"
                                >
                                  • {{ item.issues }}
                                </div>
                              </div>
                            </div>
                          </div>

                          <div class="avatar">
                            <img
                              src="@/assets/img/customer-service.png"
                              alt=""
                            >
                          </div>
                        </div>
                      </div>
                      <div
                        v-if="!m.send&&!m.content.text.sender&&m.content.text?.msgType!==-1"
                        :id="m.clientMsgNo"
                        class="message-left"
                      >
                        <div
                          v-if="!m.content.text.type"
                          class="message-content"
                        >
                          <div
                            class="avatar"
                          >
                            <img
                              v-if="getChannelInfo(m,'pic')"

                              :src="checkFileUrl(getChannelInfo(m,'pic'))"
                              alt=""
                            >
                            <img
                              v-else
                              src="~@/assets/img/userImg.jpg"
                              alt=""
                            >
                          </div>
                          <div
                            class="bubble-left"
                          >
                            <div
                              v-if="m.content.text.msgType===1"
                              class="bubble-content"
                            >
                              {{ getMessageText(m) }}
                            </div>
                            <div
                              v-if="m.content.text.msgType===2"
                              class="bubble-content"
                              @tap="showPic(checkFileUrl(m.content.text.msg))"
                            >
                              <el-image
                                :src="checkFileUrl(m.content.text.msg)"
                                class="longimage"
                                :preview-src-list="[checkFileUrl(m.content.text.msg)]"
                              />
                            </div>
                            <div
                              v-if="m.content.text?.msgType===4"
                              class="prod-link"
                            >
                              <div
                                v-if="m.content.text.msg.orderFlag"
                                class="prod-number"
                                @click="toProdDetail(m.content.text.msg,1)"
                              >
                                {{ $t('distribIncome.orderNumber') }}:{{ m.content.text.msg.orderNumber }}
                              </div>
                              <div
                                class="link-prod prod-no"

                                @click="toProdDetail(m.content.text.msg,m.content.text.msg.orderFlag ? 1 : 0,m.content.text.msg.orderType)"
                              >
                                <img-show
                                  :src="m.content.text.msg.imgs"
                                  alt=""
                                  :class-list="['prod-img']"
                                />
                                <div class="link-detail">
                                  <div class="prod-name">
                                    {{ m.content.text.msg.prodName }}
                                  </div>
                                  <div class="prod-price">
                                    <span>
                                      {{ m.content.text.msg.actualTotal ? '￥' : '' }}
                                      {{ m.content.text.msg.actualTotal ? m.content.text.msg.actualTotal : '' }}
                                      {{ (m.content.text.msg.actualTotal && m.content.text.msg.useScore) ? '+' : '' }}
                                      <span v-if="m.content.text.msg.useScore">
                                        {{ m.content.text.msg.useScore }} {{ $t('prodDetail.points') }}
                                      </span>
                                    </span>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                      <!-- 商家-平台发送的消息end -->
                    </template>
                  </div>
                </div>

                <!-- 下方发送信息栏 -->
                <div class="reply">
                  <div class="small-box">
                    <div class="upload" />
                    <div
                      class="customerService"
                      @click="customerService()"
                    >
                      {{ $t('chat.transferToCustomerService') }}
                      <el-tooltip
                        effect="dark"
                        :content="$t('chat.transferTips')"
                        placement="right"
                      >
                        <el-icon><QuestionFilled /></el-icon>
                      </el-tooltip>
                    </div>
                  </div>
                  <label
                    for="iii"
                    class="imgUp"
                  ><a
                    class="upload"
                    style="cursor: pointer"
                  /></label>
                  <input
                    id="iii"
                    ref="fileRef"
                    accept="image/png, image/jpeg"
                    type="file"
                    class="search-btnn"
                    @change="toolEvent"
                  >
                  <div class="reply-area">
                    <textarea
                      id=""
                      v-model="textMsg"
                      name=""
                      cols="20"
                      rows="4"
                      @keydown="messageSendlisten($event)"
                    />
                  </div>
                  <div
                    class="send"
                    @click="sendText()"
                  >
                    {{ $t('chat.send') }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 放大图片栏 -->

    <!-- 转接客服弹窗 -->
    <el-dialog
      v-model="visible"
      :title="$t('chat.selectOnlineCustomerService')"
      :modal="false"
      top="60px"
      width="800px"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="prods-select-body">
        <div class="username">
          {{ $t('homes.userName') }}
        </div>
        <div
          v-for="item in serviceList"
          :key="item.uid"
          class="service-list"
        >
          <el-radio
            v-model="platformUserId"
            :label="item.uid"
            @change="getSelectProdRow(item)"
          >
            &nbsp;
          </el-radio>
          <span class="nick-name">{{ item.nickName }}</span>
        </div>
        <div
          v-if="serviceList.length===0"
          class="no-data"
        >
          {{ $t('order.noData') }}
        </div>
      </div>
      <template #footer>
        <span>
          <el-button @click="visible = false">{{
            $t("crud.filter.cancelBtn")
          }}</el-button>
          <el-button
            type="primary"
            @click="transferDetermination()"
          >{{
            $t("crud.filter.submitBtn")
          }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { uploadFile } from '@/utils/http.js'
import { Convert } from './components/Conversation/convert'
import cookie from 'vue-cookies'
import { ElMessage } from 'element-plus'
import { ConnectStatus, WKSDK, Message, MessageText, MessageStatus, PullMode } from 'wukongimjssdk'
import Conversation from './components/Conversation/index.vue'

const route = useRoute()
const router = useRouter()
// 防止订单页面跳转过来数据不对应
watch(() => route.query, (to, from) => {
  if (to !== from) {
    location.reload()
  }
})

onMounted(() => {
  getWuKong()
  getSensitiveWords()
  WKSDK.shared().chatManager.addCMDListener(cmdListener) // 监听cmd消
})

let messageReminding = true // 存放标题闪烁定时器
onUnmounted(() => {
  clearInterval(messageReminding)
  WKSDK.shared().connectManager.removeConnectStatusListener(connectStatusListener)
  WKSDK.shared().chatManager.removeMessageListener(messageListener)
  WKSDK.shared().chatManager.removeCMDListener(cmdListener)
  WKSDK.shared().chatManager.removeMessageStatusListener(messageStatusListener)
  WKSDK.shared().disconnect()
})
const defaultTitle = document.title // 存储默认标题

window.addEventListener('visibilitychange', () => {
  clearInterval(messageReminding)
  document.title = defaultTitle
})
// 清除消息提醒时器
const clearMeagess = () => {
  clearInterval(messageReminding)
  document.title = defaultTitle
}

// 消息提醒标题闪烁
const messageRemindingFn = () => {
  window.onfocus = () => {
    clearMeagess()
  }
  clearInterval(messageReminding)
  messageReminding = setInterval(() => {
    const title = document.title
    // 如果没有获取焦点就判断名称是否包含未读消息
    if (/您有新消息/.test(title) === false) {
      // 如果包含就显示为空
      document.title = '【您有新消息】'
    } else {
      // 否则显示未读消息，间隔0.5秒实现闪烁
      document.title = defaultTitle
    }
  }, 500)
}
let noAccountable = true // 转接判断
const serviceList = ref([])

const visible = ref(false) // 客服转接弹窗显隐
/**
 * 转接客服
 */
const customerService = () => {
  if (isDestroy || isDestroyArr.includes(to.value.channelID)) {
    ElMessage.error('账户已注销')
    textMsg.value = ''
    return
  }
  if (!to.value.channelID) return
  if (!noAccountable) {
    ElMessage.error($t('chat.notYourResponsibility'))
    return
  }
  http.get('/platform/wuKongIm/listTransfer').then(({ data }) => { // 客服列表
    serviceList.value = data
  })
  const time = setTimeout(() => {
    if (noAccountable) visible.value = true
    visible.value = true
    clearTimeout(time)
  }, 100)
}

const isJSON = (str) => {
  if (typeof str === 'string') {
    try {
      JSON.parse(str)
      return true
    } catch (e) {
      return false
    }
  }
}

/**
 * textarea回车事件
 */
const messageSendlisten = (event) => {
  if (event.keyCode === 13) {
    sendText() // 发送文本
    event.preventDefault() // 阻止浏览器默认换行操作
    return false
  }
}

const textMsg = ref('')
let sensitiveWords = '' // 敏感词
/**
 * 发送文本消息
 */
const sendText = () => {
  if (!to.value.channelID) return
  if (isDestroy || isDestroyArr.includes(to.value.channelID)) {
    ElMessage.error('账户已注销')
    textMsg.value = ''
    return
  }
  if (!noAccountable) {
    ElMessage.error($t('chat.notYourResponsibility'))
    textMsg.value = ''
    return
  }
  if (textMsg.value === '' || textMsg.value.match(/^\s+$/)) {
    ElMessage({
      message: $t('chat.cannotSendBlankMessage'),
      type: 'warning'
    })
    return
  }
  if (sensitiveWords) {
    try {
      const rep = new RegExp(sensitiveWords, 'g')
      textMsg.value = textMsg.value.replaceAll(rep, '**')
    } catch (e) {}
  }

  let content = ''
  const msgObj = JSON.stringify({ msg: textMsg.value, msgType: 1, sender: -1 })
  content = new MessageText(msgObj)
  WKSDK.shared().chatManager.send(content, to.value)
  textMsg.value = ''
}

const fileRef = ref(null)
// 发送图片
const toolEvent = () => {
  if (!to.value.channelID) return
  if (isDestroy || isDestroyArr.includes(to.value.channelID)) {
    ElMessage.error('账户已注销')
    textMsg.value = ''
    return
  }
  if (!noAccountable) {
    ElMessage.error($t('chat.notYourResponsibility'))
    return
  }
  let selectFileobj = {}
  if (fileRef.value?.files[0]) {
    selectFileobj = fileRef.value?.files[0]
  }
  http({
    url: http.adornUrl('/admin/file/getPreSignUrl'),
    method: 'get',
    params: http.adornParams({
      fileName: selectFileobj.name,
      isImFile: true
    })
  }).then(({ data }) => {
    uploadFile(data.preSignUrl, selectFileobj).then(() => {
      http({
        url: http.adornUrl('/admin/file/uploadSuccess'),
        method: 'put',
        data: [{
          fileId: data.fileId,
          attachFileGroupId: 0,
          fileSize: selectFileobj.size
        }]
      }).then(() => {
        fileRef.value.value = null // 解决上传同一图片不显示bug=
        const msgObj = JSON.stringify({ msg: data.filePath, msgType: 2 })
        const content = new MessageText(msgObj)
        WKSDK.shared().chatManager.send(content, to.value)
        scrollBottom()
      })
    })
  })
}

/**
 * 进行相隔时间判断
 * true 删除显示时间
 * false 保留显示时间
 */
const timeBeApart = (uppTime, preTime) => {
  if (!uppTime) {
    return false
  }
  const dateDiff = preTime - uppTime// 时间差的毫秒数
  const dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000))// 计算出相差天数
  const leave1 = dateDiff % (24 * 3600 * 1000) // 计算天数后剩余的毫秒数
  const hours = Math.floor(leave1 / (3600 * 1000))// 计算出小时数
  // 计算相差分钟数
  const leave2 = leave1 % (3600 * 1000) // 计算小时数后剩余的毫秒数
  const minutes = Math.floor(leave2 / (60 * 1000))// 计算相差分钟数

  return !(dayDiff >= 1 || hours >= 1 || minutes > 4)
}

/**
 * 改变日期
 */
const tsToDate = (number, format) => {
  const formateArr = ['Y', 'M', 'D', 'h', 'm', 's']
  const returnArr = []

  const date = new Date(number)
  returnArr.push(date.getFullYear())
  returnArr.push(
    date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  )
  returnArr.push(
    date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  )

  returnArr.push(
    date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  )
  returnArr.push(
    date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  )
  returnArr.push(
    date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  )

  for (const i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i])
  }
  return format
}

const platformUserId = ref(0)
// 选中客服
const getSelectProdRow = (row) => {
  platformUserId.value = row.uid
}

/**
 * 转接客服确定
 */
const conversationRef = ref(null)
const transferDetermination = () => {
  if (!noAccountable) {
    ElMessage.error($t('chat.notYourResponsibility'))
    return
  }
  if (platformUserId.value) {
    http.post('/platform/wuKongIm/transfer?channelId=' + to.value.channelID + '&uid=' + platformUserId.value).then(async () => {
      await WKSDK.shared().channelManager.fetchChannelInfo(to.value)
      ElMessage.success($t('chat.transferToCustomerService') + $t('order.success'))
      visible.value = false
      // eslint-disable-next-line require-atomic-updates
      to.value.channelID = ''
      messages.value = []
      userName.value = ''
      conversationRef.value.resetConversation()
    })
  } else {
    ElMessage.error($t('chat.pleaseSelectAcustomerService'))
  }
  platformUserId.value = 0
}

/**
 * 链接点击去往商品详情或订单详情
 */
const toProdDetail = (prodInfo, type, orderType) => {
  let routeUrl
  if (type || prodInfo.orderFlag) {
    if (orderType === 3) {
      routeUrl = router.resolve({
        path: '/member/score/order/info',
        query: {
          orderNumber: prodInfo.orderNumber
        }
      })
    } else {
      routeUrl = router.resolve({
        path: '/order/order-info/index',
        query: {
          orderNumber: prodInfo.orderNumber
        }
      })
    }
  } else {
    let prodName = prodInfo.prodName
    const skuName = prodInfo.skuName
    const prodId = prodInfo.prodId

    if (skuName) {
      let prodNameArray = prodName.split(' ')
      const skuNameArray = skuName.split(' ')
      // 过滤掉sku名称
      prodNameArray = prodNameArray.filter(item => {
        return skuNameArray.every(item1 => {
          return item !== item1
        })
      })

      prodName = prodNameArray.join('')
    }
    if (orderType === 3) {
      routeUrl = router.resolve({
        path: '/member/score/prod/list',
        query: {
          prodName,
          prodId
        }
      })
    } else {
      routeUrl = router.resolve({
        path: '/prod/prod-list/index',
        query: {
          prodName,
          prodId
        }
      })
    }
  }
  window.open(routeUrl.href, '_blank', 'noopener,noreferrer')
}

const getSensitiveWords = () => {
  http({
    url: http.adornUrl('/sys/pconfig/info/SENSITIVE_WORDS'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    data = JSON.parse(data)
    if (data?.sensitiveWord) {
      sensitiveWords = data.sensitiveWord.replaceAll('，', '|')
    }
  })
}
const chatRef = ref(null)
const scrollBottom = () => {
  const chat = chatRef.value
  if (chat) {
    nextTick(function () {
      chat.scrollTop = chat.scrollHeight
    })
  }
}
const userStore = useUserStore()
const channelId = computed(() => userStore.channelId)
window.addEventListener('beforeunload', () => {
  const temp = cookie.get('bbcVpChannelIds')
  if (Number(temp) > 0) {
    const updateNum = Number(temp) - channelId.value
    cookie.set('bbcVpChannelIds', updateNum)
  }
})
// 悟空IM
const title = ref('')
let messageStatusListener
let connectStatusListener
let messageListener
const messages = ref([])
const getWuKong = () => {
  http.post('/platform/wuKongIm/registerOrLogin?token=' + cookie.get('bbcAuthorization_vp')).then(({ data }) => {
    // 认证信息
    const config = WKSDK.shared().config
    config.addr = import.meta.env.VITE_APP_WS_IM_API
    config.uid = data.uid // 用户uid（需要在悟空通讯端注册过）
    config.token = data.token// 用户token （需要在悟空通讯端注册过）
    WKSDK.shared().config = config
    WKSDK.shared().connect()

    // 监听连接状态
    connectStatusListener = (status) => {
      if (status === ConnectStatus.Connected) {
        title.value = '(连接成功)'
      } else {
        title.value = '(断开)'
      }
    }
    WKSDK.shared().connectManager.addConnectStatusListener(connectStatusListener)
    // 监听消息
    messageListener = (msg) => {
      if (isJSON(msg.content.text)) {
        msg.content.text = JSON.parse(msg.content.text)
      }
      const type = msg.content.text.type
      if (msg.send && type !== -1 && msg.content.text.msgType !== -1 && updateAuto) {
        http.post('/platform/wuKongIm/updateAuto?channelId=' + msg.channel.channelID)
        updateAuto = false
      }
      if (!msg.send && msg.content.text.sender !== 1 && msg.content.text.sender !== -1) {
        messageRemindingFn()
      }

      msg.messageSeq = ++lastMessageSeq // 新发送的消息没有序列号,此处添加序列号
      if (msg.channel.channelID === to.value.channelID) {
        http.post('/platform/wuKongIm/conversations/setUnread', { channel_id: to.value.channelID, maxSeq: lastMessageSeq || 0 })
      }
      if (to.value.channelID === msg.channel.channelID) {
        if (msg.content.text.sender === 1) {
          http.post('/platform/wuKongIm/getShopChannelInfo?userId=' + selectedID).then(({ data }) => {
            noAccountable = data.isWhiteUser === 1
          })
        }
        if (messages.value.length) {
          const prevTime = tsToDate(
            messages.value[messages.value.length - 1].timestamp * 1000,
            'M月D日 h:m'
          )
          const nowTime = tsToDate(new Date().getTime(), 'M月D日 h:m')
          if (prevTime.slice(0, prevTime.indexOf(' ')) === nowTime.slice(0, nowTime.indexOf(' '))) {
            msg.timeStr = tsToDate(new Date().getTime(), 'h:m')
          } else {
            msg.timeStr = tsToDate(new Date().getTime(), 'M月D日 h:m')
          }
          const timeFlag = timeBeApart(messages.value[messages.value.length - 1].timestamp * 1000, new Date().getTime())
          if (timeFlag) {
            delete msg.timeStr
          }
        } else {
          msg.timeStr = tsToDate(new Date().getTime(), 'M月D日 h:m')
        }
        if (!to.value.isEqual(msg.channel)) {
          return
        }
        messages.value.push(msg)
        scrollBottom()
      }
    }
    WKSDK.shared().chatManager.addMessageListener(messageListener)
    messageStatusListener = (ack) => {
      messages.value.forEach((m) => {
        if (m.clientSeq === ack.clientSeq) {
          m.status = ack.reasonCode === 1 ? MessageStatus.Normal : MessageStatus.Fail
        }
      })
    }
    WKSDK.shared().chatManager.addMessageStatusListener(messageStatusListener)
  })
}
const to = ref({})
const maxReadSeq = ref(0)
let lastMessageSeq = 0
const userName = ref('')
let updateAuto = false
let selectedID = 0
let isDestroy = 0
// eslint-disable-next-line max-params
const onSelectChannel = async (channel, maxSeq, noAccount, nickName, update, userId, destroy) => {
  isDestroy = destroy
  selectedID = userId
  userName.value = nickName
  updateAuto = update
  noAccountable = noAccount === 1
  maxReadSeq.value = maxSeq
  clearMeagess()
  to.value = channel
  messages.value = []
  pullLast(channel) // 拉取最新消息
}
const pulldowning = ref(false) // 下拉中
const pulldownFinished = ref(false) // 下拉完成
const pullLast = async () => {
  pulldowning.value = true
  pulldownFinished.value = false
  const msgs = await WKSDK.shared().chatManager.syncMessages(to.value, {
    limit: 15,
    startMessageSeq: 0,
    endMessageSeq: 0,
    pullMode: PullMode.Up
  })
  console.log('🚀 ~ msgs ~ msgs:', msgs)
  lastMessageSeq = msgs[msgs.length - 1]?.messageSeq || msgs[msgs.length - 2]?.messageSeq || 0
  pulldowning.value = false

  if (msgs && msgs.length > 0) {
    msgs.forEach((m) => {
      messages.value.push(m)
    })
  }
  scrollBottom()
}
// 同步自己业务端的频道消息列表
WKSDK.shared().config.provider.syncMessagesCallback = async (channel, opts) => {
  const resultMessages = []
  const limit = 20
  const { data } = await http.post('/platform/wuKongIm/channel/messageSync', {
    channel_id: channel.channelID,
    channel_type: channel.channelType,
    start_message_seq: opts.startMessageSeq,
    end_message_seq: opts.endMessageSeq,
    pull_mode: opts.pullMode,
    limit
  })
  const messageList = data && data.messages
  if (messageList) {
    messageList.forEach((msg) => {
      const message = Convert.toMessage(msg)
      message.content.text = JSON.parse(message.content.text)
      message.timeStr = tsToDate(
        message.timestamp * 1000,
        'M月D日 h:m'
      )
      resultMessages.push(message)
    })

    resultMessages.length > 0 && resultMessages.reduce((prev, cur) => {
      // 将时间更换为某某月某某日 要是是当天即去掉月日
      const now = tsToDate(prev.timestamp * 1000, 'M月D日 h:m')
      const next = tsToDate(cur.timestamp * 1000, 'M月D日 h:m')
      if (
        now.slice(0, now.indexOf(' ')) ===
            next.slice(0, next.indexOf(' '))
      ) {
        cur.timeStr = tsToDate(cur.timestamp * 1000, 'h:m')
      }

      // 历史记录进行时间段显示判断
      if (resultMessages.length > 2) {
        const timeFlag = timeBeApart(prev.timestamp * 1000, cur.timestamp * 1000)
        if (timeFlag) {
          delete cur.timeStr
        }
      }
      return cur
    })
  }

  return resultMessages
}

const getMessageText = (m) => {
  if (m instanceof Message) {
    const streams = m.streams
    let text = ''
    if (m.content instanceof MessageText) {
      const messageText = m.content
      text = messageText.text.msg || ''
    }
    if (streams && streams.length > 0) {
      for (const stream of streams) {
        if (stream.content instanceof MessageText) {
          const messageText = stream.content
          text = text + (messageText.text.msg || '')
        }
      }
    }
    return text
  }
  return '未知消息'
}
const channelInfo = ref([])
const getChannelInfo = (m, temp) => {
  channelInfo.value = WKSDK.shared().channelManager.getChannelInfo(m.channel)// 获取频道详情(不会触发数据源的远程获取)
  let info = channelInfo.value.data.find((item) => m.fromUID === item.uid)
  if (!info) {
    info = channelInfo.value.data[0] // 客服被删除使用超管的信息
  }
  if (info) {
    return info[temp]
  }
}
const { proxy } = getCurrentInstance()
const channelInfoUpdate = () => {
  proxy.$forceUpdate()
}
const handleScroll = (e) => {
  const targetScrollTop = e.target.scrollTop
  if (targetScrollTop <= 250) { // 下拉
    if (pulldowning.value || pulldownFinished.value) {
      return
    }
    pulldowning.value = true
    pullDown().then(() => {
      pulldowning.value = false
    }).catch(() => {
      pulldowning.value = false
    })
  }
}
const pullDown = async () => {
  if (messages.value.length === 0) {
    return
  }
  const firstMsg = messages.value[0]
  if (firstMsg.messageSeq === 1) {
    pulldownFinished.value = true
    return
  }
  const limit = 15
  const msgs = await WKSDK.shared().chatManager.syncMessages(to.value, {
    limit,
    startMessageSeq: firstMsg.messageSeq - 1,
    endMessageSeq: 0,
    pullMode: PullMode.Down
  })
  if (msgs.length < limit) {
    pulldownFinished.value = true
  }
  if (msgs && msgs.length > 0) {
    msgs.reverse().forEach((m) => {
      messages.value.unshift(m)
    })
  }
  nextTick(function () {
    const chat = chatRef.value
    const firstMsgEl = document.getElementById(firstMsg.clientMsgNo)
    if (firstMsgEl) {
      chat.scrollTop = firstMsgEl.offsetTop
    }
  })
}
const isDestroyArr = ([])
const cmdListener = async (msg) => {
  if (isJSON(msg.content.contentObj.content)) {
    msg.content.contentObj.content = JSON.parse(msg.content.contentObj.content)
    if (msg.content.contentObj.content.type === -2) {
      maxReadSeq.value = msg.content.contentObj.content.content// 已读的最大序列号
    }
  }
  if (msg.content.contentObj.cmd === 'userDestroy') {
    isDestroyArr.push(msg.content.contentObj.param)
  }
}
</script>
<style lang="scss" scoped>
@use "index";
</style>
